// 基础请求模块 - 处理HTTP请求、平台适配、网络状态检查
import config from '../config.js'
import appStateManager from '../app-state-manager.js'
import { recordLog } from '../api-logger.js'

class BaseAPI {
    constructor() {
        // 使用环境配置获取服务器地址
        this.baseURL = config.getServerURL();
        this.environmentInfo = config.getEnvironmentInfo();
        this.retryCount = 0;
        this.maxRetries = 1;
        this.retryDelay = 500;
        
        console.log('API服务初始化:', {
            environment: this.environmentInfo.environment,
            platform: this.environmentInfo.platform,
            serverURL: this.baseURL,
            isDevelopment: this.environmentInfo.isDevelopment
        });
        
        // 监听服务器状态变化
        appStateManager.onStatusChange((isOnline) => {
            // 减少日志输出，只在状态真正改变时输出
            if (this.isOnline !== isOnline) {
                console.log('API服务收到服务器状态变化:', isOnline ? '在线' : '离线');
                this.isOnline = isOnline;
            }
        });
    }
    
    // 获取当前平台
    getPlatform() {
        return config.getPlatform();
    }
    
    // 获取网络信息
    getNetworkInfo() {
        return new Promise((resolve) => {
            const platform = this.getPlatform();
            
            if (platform === 'web') {
                // 网页端直接返回网络连接状态
                const isOnline = navigator.onLine;
                resolve({
                    networkType: isOnline ? 'wifi' : 'none',
                    isConnected: isOnline
                });
            } else {
                // App端使用uni.getNetworkType
                uni.getNetworkType({
                    success: (res) => {
                        resolve({
                            networkType: res.networkType,
                            isConnected: res.networkType !== 'none'
                        });
                    },
                    fail: () => {
                        resolve({
                            networkType: 'unknown',
                            isConnected: false
                        });
                    }
                });
            }
        });
    }

    // GET请求方法
    async get(url, options = {}) {
        // 对于健康检查请求，总是尝试连接服务器，不依赖isOnline状态
        if (url === '/health') {
            return this.requestHealthCheck();
        }
        return this.request(url, {
            method: 'GET',
            ...options
        });
    }

    // 健康检查请求方法（总是尝试连接服务器）
    async requestHealthCheck() {
        try {
            const platform = this.getPlatform();
            let result;
            
            if (platform === 'web') {
                // 网页端使用fetch
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 5000); // 5秒超时
                
                const response = await fetch(`${this.baseURL}/health`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    signal: controller.signal
                });
                
                clearTimeout(timeoutId);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                
                result = await response.json();
            } else {
                // App端使用uni.request
                result = await new Promise((resolve, reject) => {
                    uni.request({
                        url: `${this.baseURL}/health`,
                        method: 'GET',
                        timeout: 5000,
                        success: (res) => {
                            if (res.statusCode === 200) {
                                resolve(res.data);
                            } else {
                                reject(new Error(`HTTP error! status: ${res.statusCode}`));
                            }
                        },
                        fail: (error) => {
                            reject(error);
                        }
                    });
                });
            }
            
            return result;
        } catch (error) {
            console.error('健康检查请求失败:', error);
            throw error;
        }
    }

    // 带重试的请求方法
    async request(url, options = {}) {
        // 如果服务器离线，仅登录/注册允许走本地处理
        const serverStatus = appStateManager.getStatus();
        console.log('API请求检查服务器状态:', {
            url: url,
            isOnline: serverStatus.isOnline,
            statusChecked: serverStatus.statusChecked,
            lastCheckTime: serverStatus.lastCheckTime
        });
        
        if (!serverStatus.isOnline) {
            const startTime = Date.now();
            if (url === '/login' || url === '/register') {
                // 这里需要调用 auth 模块的本地处理方法，暂时先抛出错误
                const duration = Date.now() - startTime;
                recordLog({
                    type: 'offline',
                    method: options.method || 'GET',
                    url,
                    status: 'OFFLINE',
                    success: false,
                    errorMessage: '服务器离线，请使用在线模式',
                    durationMs: duration
                });
                throw new Error('服务器离线，无法完成请求');
            }
            const duration = Date.now() - startTime;
            recordLog({
                type: 'network',
                method: options.method || 'GET',
                url,
                status: 'OFFLINE',
                success: false,
                errorMessage: '服务器离线，无法完成请求',
                durationMs: duration
            });
            throw new Error('服务器离线，无法完成请求');
        }

        try {
            const platform = this.getPlatform();
            let result;
            const startTime = Date.now();
            
            if (platform === 'web') {
                // 网页端使用fetch
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 15000); // 15秒超时
                
                const response = await fetch(`${this.baseURL}${url}`, {
                    method: options.method || 'GET',
                    headers: {
                        'Content-Type': 'application/json',
                        ...options.headers
                    },
                    body: options.body || undefined,
                    signal: controller.signal
                });
                
                clearTimeout(timeoutId);
                
                if (!response.ok) {
                    // 尝试获取服务器返回的错误详情
                    let errorMessage = `HTTP error! status: ${response.status}`;
                    try {
                        const errorData = await response.json();
                        if (errorData.code && errorData.message) {
                            errorMessage = JSON.stringify(errorData);
                        }
                    } catch (jsonError) {
                        console.log('无法解析服务器错误响应:', jsonError);
                    }
                    const duration = Date.now() - startTime;
                    recordLog({
                        type: 'network',
                        method: options.method || 'GET',
                        url,
                        status: response.status,
                        success: false,
                        errorMessage,
                        durationMs: duration
                    });
                    const error = new Error(errorMessage);
                    error.status = response.status;
                    throw error;
                }
                
                const responseData = await response.json();
                const duration = Date.now() - startTime;
                recordLog({
                    type: 'network',
                    method: options.method || 'GET',
                    url,
                    status: 200,
                    success: true,
                    durationMs: duration
                });
                result = { data: responseData };
            } else {
                // App端使用uni.request
                result = await new Promise((resolve, reject) => {
                    const start = Date.now();
                    uni.request({
                        url: `${this.baseURL}${url}`,
                        method: options.method || 'GET',
                        data: options.body ? JSON.parse(options.body) : undefined,
                        header: {
                            'Content-Type': 'application/json',
                            ...options.headers
                        },
                        timeout: 10000,
                        success: (res) => {
                            const duration = Date.now() - start;
                            if (res.statusCode >= 200 && res.statusCode < 300) {
                                recordLog({
                                    type: 'network',
                                    method: options.method || 'GET',
                                    url,
                                    status: res.statusCode,
                                    success: true,
                                    durationMs: duration
                                });
                                resolve(res);
                            } else {
                                let errorMessage = `HTTP error! status: ${res.statusCode}`;
                                if (res.data && res.data.code && res.data.message) {
                                    errorMessage = JSON.stringify(res.data);
                                }
                                recordLog({
                                    type: 'network',
                                    method: options.method || 'GET',
                                    url,
                                    status: res.statusCode,
                                    success: false,
                                    errorMessage,
                                    durationMs: duration
                                });
                                const error = new Error(errorMessage);
                                error.status = res.statusCode;
                                reject(error);
                            }
                        },
                        fail: (error) => {
                            const duration = Date.now() - start;
                            recordLog({
                                type: 'network',
                                method: options.method || 'GET',
                                url,
                                status: 'NETWORK_FAIL',
                                success: false,
                                errorMessage: (error && error.errMsg) || (error && error.message) || 'request failed',
                                durationMs: duration
                            });
                            reject(error);
                        }
                    });
                });
            }

            this.retryCount = 0; // 重置重试计数
            console.log('API请求成功，返回数据:', result.data);
            return result.data;
        } catch (error) {
            console.error('API请求失败:', error);
            if (url === '/register' && (error.status === 400 || error.status === 409)) {
                console.log('注册请求被服务器拒绝，不进行重试');
                throw error;
            }
            // 重试策略：不再做本地回退
            if (url === '/login' || url === '/register') {
                if (this.retryCount < 1) {
                    this.retryCount++;
                    console.log(`重试第 ${this.retryCount} 次...`);
                    await this.delay(this.retryDelay);
                    return this.request(url, options);
                }
            } else {
                if (this.retryCount < this.maxRetries) {
                    this.retryCount++;
                    console.log(`重试第 ${this.retryCount} 次...`);
                    await this.delay(this.retryDelay * this.retryCount);
                    return this.request(url, options);
                }
            }
            // 重试耗尽，记录并抛错
            recordLog({
                type: 'network',
                method: options.method || 'GET',
                url,
                status: 'RETRY_EXCEEDED',
                success: false,
                errorMessage: error && error.message,
                durationMs: 0
            });
            throw error;
        }
    }

    // 延迟函数
    delay(ms) {
        return new Promise(resolve => setTimeout(resolve, ms));
    }

    // 获取服务器状态
    getServerStatus() {
        return appStateManager.getStatus();
    }
    
    // 手动刷新服务器状态
    async refreshServerStatus() {
        return await appStateManager.refreshStatus();
    }
    
    // 监听服务器状态变化
    onServerStatusChange(callback) {
        appStateManager.onStatusChange(callback);
    }

    // 监听服务器状态变化（委托给服务器状态管理器）
    onStatusChange(callback) {
        return appStateManager.onStatusChange(callback);
    }
    
    // 移除服务器状态变化监听（委托给服务器状态管理器）
    offStatusChange(callback) {
        return appStateManager.offStatusChange(callback);
    }
}

// 创建全局实例
const baseAPI = new BaseAPI();

export default baseAPI; 